import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo,reqLogout } from '@/api/user/index'
import { ResponseData, loginResponseData } from '@/api/user/type'
// 引入相关的接口类型
import type { UserState } from './types/type'
//引入路由(常量路由)
import { constantRoute } from '@/router/routes'

export const useUserStore = defineStore({
  id: 'user',
  status: () : UserState => {
    return {
      token: (localStorage.getItem('token') as string), //用户唯一标识token
      constantRoute: constantRoute, //仓库存储生成菜单需要数组(路由)
      username: '',
      avatar: '',
    }
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: ResponseData) {
      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      let result: loginResponseData = await reqLogin(data)
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = (result.data as string);
        localStorage.setItem('token', result.data)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息方法
    async userInfo() {
      let res = await reqUserInfo()
       //如果获取用户信息成功，存储一下用户信息
      if(res.code == 200) {
        this.username = res.data.name;
        localStorage.setItem('username', res.data.name)
        this.avatar = res.data.avatar;
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    //退出登录
    async userLogout() {
      //退出登录请求
      let res: any =  await reqLogout()
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      if (res.code === 200) {
        //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
        this.token = ''
        this.username = ''
        this.avatar = ''
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    }
  }
})

